let COS = require('cos-js-sdk-v5');
import uuidv1 from 'uuid/v1'
import { mainApi } from '@/api/index.js'
import SparkMD5 from  'spark-md5'


let cos = new COS({
    getAuthorization: function (options, callback) {  // 异步获取临时密钥
        mainApi.get('/pan/file/token/v1').then(function (data) {
            if (data.data.code === 1) {
                callback({
                    TmpSecretId: data.data.data.credentials.tmpSecretId,        // 临时密钥的 tmpSecretId
                    TmpSecretKey: data.data.data.credentials.tmpSecretKey,      // 临时密钥的 tmpSecretKey
                    XCosSecurityToken: data.data.data.credentials.sessionToken, // 临时密钥的 sessionToken
                    ExpiredTime: data.data.data.expiredTime,               // 临时密钥失效时间戳，是申请临时密钥时，时间戳加 durationSeconds
                });
            } else {
                throw 'get tencent upload key error'
            }
        })
    }
});
let uploadFile = function (fileData,callback) {
    cos.sliceUploadFile({
        Bucket: "ddbes-pan-tmp-1257239906",
        Region: "ap-beijing",
        Key: uuidv1(),
        Body: fileData,
        onTaskReady: function (taskId) {  //监听任务创建
            // 任务开始
            console.log(taskId)
        },
        onProgress: function (progressData) {
            //   进度
            console.log(progressData)
        }
    }, function (err, data) {
        callback(err, data)
    });
}

let md5 = function(file,callback) {
    let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
      chunkSize = 2097152,                             // Read in chunks of 2MB
      chunks = Math.ceil(file.size / chunkSize),
      currentChunk = 0,
      spark = new SparkMD5.ArrayBuffer(),
      fileReader = new FileReader();

    fileReader.onload = function (e) {
        spark.append(e.target.result);                   // Append array buffer
        currentChunk++;
        if (currentChunk < chunks) {
            loadNext();
        } else {
            callback(spark.end())
            console.info('computed hash', );  // Compute hash
        }
    };

    fileReader.onerror = function () {
        console.warn('oops, something went wrong.');
    };

    function loadNext() {
        var start = currentChunk * chunkSize,
          end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
    }
    loadNext();
}





export { uploadFile ,md5};
